package xyz.mimai.media.netty.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @ClassName SimpleHttpServer
 * @Description 基于netty的一个简单http服务器示例，使用浏览器替代客户端访问，譬如:http://127.0.0.1?params1=AAAA&&params2=BBB
 * @Author 方丈
 * @Date 2021/2/5 9:21
 * @Version 1.0.0
 **/
public class SimpleHttpServer {
    public static void main(String[] args) {
        //创建主线程组，只处理连接请求
        EventLoopGroup eventBossGroup = new NioEventLoopGroup(1) ;
        //创建工作线，接收主线程分发过来的任务，完成实际的工作                                                                                                                   程组
        EventLoopGroup eventWorkGroup = new NioEventLoopGroup(3) ;

        ServerBootstrap serverBootstrap = new ServerBootstrap()
                .group(eventBossGroup,eventWorkGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new HttpServerChannelInitializer());
        try {
            ChannelFuture channelFuture = serverBootstrap.bind(80).sync();
            //添加注册监听，监控关心的事件，当异步处理结束后，会回调监听逻辑
            channelFuture.addListener(
                    (ChannelFutureListener) channelFuture1 -> {
                        if(channelFuture1.isSuccess()){
                            System.out.println("成功启动http服务");
                        }else{
                            System.out.println("启动http服务失败... ...");
                        }
                        if(channelFuture.isDone()){
                            System.out.println("http服务发布成功，正式服务...");
                        }
                    }

            );

            channelFuture.channel().closeFuture().sync();
        }catch (InterruptedException ine){
            ine.printStackTrace();
        }finally {
            eventBossGroup.shutdownGracefully();
            eventWorkGroup.shutdownGracefully();
        }
    }


}
